package logic

import (
	"context"
	"errors"
	"refister-kit/model/cache"
	"refister-kit/model/mysql"
	"refister-kit/pkg"

	"refister-kit/registerrpc/internal/svc"
	"refister-kit/registerrpc/registerrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *registerrpc.RegisterRequest) (*registerrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	mysql.DB.Debug().Where("account = ?", in.Account).Find(&user)
	if user.ID != 0 {
		return nil, errors.New("当前账号已存在")
	}

	result, _ := cache.Rdb.Get(l.ctx, "SendSms"+in.Account).Result()
	if result != in.SendSms {
		return nil, errors.New("验证码错误，请重新输入")
	}

	results, _ := cache.Rdb.Get(l.ctx, "Captcha"+in.Account).Result()
	if results != in.Captcha {
		return nil, errors.New("图片验证码错误，请重新输入")
	}

	m := mysql.User{
		Account:  in.Account,
		Password: pkg.MD5(in.Password),
	}

	mysql.DB.Debug().Create(&m)

	return &registerrpc.RegisterResponse{
		UserId: int64(m.ID),
	}, nil
}
